package com.lwj.controller;


import com.lwj.annotation.Controller;
import com.lwj.annotation.RequestMapping;
import com.lwj.core.ClientHandler;
import com.lwj.entity.Article;
import com.lwj.http.HttpServletRequest;
import com.lwj.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;

/**
 * 处理与文章相关的业务
 */
@Controller
public class ArticleController {
    /**
     * 该目录用于保存所有文章信息
     */
    private static File ARTICLE_DIR = new File("./temp/articles");

    private static File staticDir;

    static {
        if (!ARTICLE_DIR.exists()) {
            ARTICLE_DIR.mkdirs();
        }
        try {
            staticDir = new File(ClientHandler.class.getClassLoader().getResource("./static").toURI());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/web/writeArticle")
    public void writeArticle(HttpServletRequest request, HttpServletResponse response) {
        //获取表单信息
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");
        if (title == null || author == null || content == null) {
            //跳错误页面
            File file = new File(staticDir, "/web/writeArticle_info_error.html");
            response.setContentFile(file);
            return;
        }
        File articleFile = new File(ARTICLE_DIR, title + ".obj");
        try(
             FileOutputStream fos = new FileOutputStream(articleFile);
             ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            Article article = new Article(title, author, content);
            oos.writeObject(article);
            System.out.println(articleFile.getPath());
            File file = new File(staticDir, "/web/writeArticle_success.html");
            response.setContentFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("/web/showAllArticle")
    public void showAllArticle(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始生成动态页面");

        System.out.println("动态页面生成完毕!");
    }
}





